<template>
  <van-uploader
    v-model="fileList"
    :before-read="beforeRead"
    :after-read="afterRead"
    :before-delete="beforeDelete"
    accept="image/*"
    :multiple="false"
    :max-size="2 * 1024 * 1024"
    @oversize="onOversize"
  />
</template>
<script setup>
import { Uploader as VanUploader } from "vant";
import { ref, watch, inject, onMounted } from "vue";
// import { apiuploadFile } from "@/api/common.js";
import Compressor from "compressorjs";
const props = defineProps({
    modelValue: {
      type: Array,
      required: true,
    },
  }),
  emit = defineEmits(["update:modelValue"]),
  fileList = ref([]),
  toast = inject("toast");

function getList() {
  if (props.modelValue.length > 0) {
    const imgs = [];
    props.modelValue.forEach(item => {
      fileList.value.push({
        url: FILE_URL + item.url,
        path: item,
      });
    });
    fileList.value.forEach(item => {
      if (!!item.fileId) {
        imgs.push(item.fileId);
      }
      if(!!item.path.id) {
        imgs.push(item.path.id)
      }
    });
    emit("update:modelValue", imgs);
  }    
}

function onOversize(file) {
  toast.msg("文件大小不能超过 2MB");
}
function beforeRead(file) {
  let quality = 1;
  const sizeM = (file.size / 1024 / 1024).toFixed(1);
  if ((Number(sizeM) >= 1) & (Number(sizeM) < 4)) {
    quality = 0.6;
  } else if ((Number(sizeM) >= 4) & (Number(sizeM) < 8)) {
    quality = 0.2;
  } else if (Number(sizeM) >= 8) {
    quality = 0;
  }
  // console.log(sizeM);
  return new Promise(resolve => {
    new Compressor(file, {
      quality,
      success(result) {
        if (Object.getPrototypeOf(result) == File.prototype) {
          resolve(result);
        } else {
          // Blob 转 File
          let files = new File([result], result.name, { type: result.type });
          resolve(files);
        }
      },
      error(err) {
        console.log(err.message);
      },
    });
  });
}
function afterRead(file) {
  uploadFile(file);
}
function uploadFile(file) {
  file.status = "uploading";
  file.message = "上传中...";
  apiUpLoadImg(file);
}
function apiUpLoadImg(file) {
  var formData = new FormData();
  formData.append("file", file.file);
  //接口需要传的参数
  apiuploadFile(formData).then(res => {
    const { originalFileName, path, fileId } = res.data;
    file.status = "success";
    file.url = FILE_URL + path;
    file.path = path;
    file.fileId = fileId;
    changeImgsValue();
  },err=>{
    console.log(err)
  })
}
function beforeDelete() {
  return true;
}
function changeImgsValue() {
  const imgs = [];
  fileList.value.forEach(item => {
    if (!!item.fileId) {
      imgs.push(item.fileId);
    }
    if(!!item.path.id) {
      imgs.push(item.path.id)
    }
  });
  emit("update:modelValue", imgs);
}
watch(
  () => fileList.value.length,
  (val, oldVal) => {
    if (val < oldVal) {
      changeImgsValue();
    }
  }
);

onMounted(()=>{
  getList()
})
</script>
